package movieGandalf.dbParser;


import java.io.BufferedReader;
import java.math.BigInteger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import movieGandalf.database.MovieTools;

public class MPAARatingsAdder implements DataReader{
	
	public int read(Connection conn, BufferedReader in){
		String line = null;
		PreparedStatement stmt = null;
		
		BigInteger movieID = null;
		Integer mpaaRatingID = null;
		String mpaaRating = null;
		String imdbName = null;

		try {
			
			stmt = conn.prepareStatement("CREATE TEMPORARY TABLE IF NOT EXISTS DbMysql06.TempMPAARatings (movieID BIGINT UNSIGNED, mpaaRatingID TINYINT UNSIGNED, PRIMARY KEY (movieID));");
			stmt.execute();
			stmt.close();
			
			stmt = conn.prepareStatement("REPLACE INTO TempMPAARatings (movieID,mpaaRatingID) VALUES(?,?)");
			
			boolean isBegin = true;
			
			int len = 0;
			int i = 0;
			
			while ((line = in.readLine()) != null){
			
				len = line.length();
				
				if (isBegin){
					if (len<25 || !line.substring(0, 25).equals("MPAA RATINGS REASONS LIST"))
						continue;
					else{
						isBegin = false;
						line = in.readLine();
						continue;
					}
				}
				
				if (len<4 || !line.substring(0,4).equals("MV: "))
					continue;
				
				line = line.substring(3,len).trim()+"\t";
				imdbName = ParserTools.getIMDBName(line);
				if (!MovieTools.movieValidator(imdbName))
					continue;
				
				line = in.readLine();
				if (len<11 || line.substring(0,10).compareToIgnoreCase("RE: Rated ")!=0)
					continue;
				
				for (i = 10;i<len;i++){
					if (line.charAt(i)==' '){
						break;
					}
				}
				
				if (i == 10)
					continue;
				
				mpaaRating = line.substring(10,i);
				if (!MovieTools.mpaaRatingValidator(mpaaRating))
					continue;
				
				mpaaRatingID = MovieTools.getMPAARatingID(conn, mpaaRating);
				if (mpaaRatingID == null)
					continue;
				
				movieID = MovieTools.getMovieID(conn, imdbName);
				if (movieID == null)
					continue;		
				
				stmt.setObject(1, movieID);
				stmt.setObject(2, mpaaRatingID);
				stmt.addBatch();
			}
			
			try{
				stmt.executeBatch();
			}
			catch(Exception e){}
			finally{
				conn.commit();
				stmt.close();
			}
			
			stmt = conn.prepareStatement("UPDATE Movies INNER JOIN TempMPAARatings ON Movies.movieID=TempMPAARatings.movieID SET Movies.mpaaRatingID = TempMPAARatings.mpaaRatingID");
			stmt.addBatch();
			try{
				stmt.executeBatch();
			}
			catch(Exception e){}
			finally{
				conn.commit();
				stmt.close();
			}
		}
		
		catch (SQLException e) {
			e.printStackTrace();
			return 0;
		}
		catch (Exception e){
			e.printStackTrace();
			return 0;
		}
		finally {
			try{
				if (stmt!=null)
					stmt.close();
				in.close();
			}
			catch(Exception e){
				return 0;
			}
		}
		
		return 1;
	}
	
}
